﻿using Newtonsoft.Json;
using System;
using System.Linq;
using AbpProjectTemplate.Utilities.Enums;

namespace AbpProjectTemplate.Utilities.Json
{
    public class EnumJsonConverter : JsonConverter
    {
        private Type GetNullableTypeOrCurrent(Type objectType)
        {
            var nullableType = Nullable.GetUnderlyingType(objectType);
            return nullableType == null
                    ? objectType
                    : nullableType;
        }

        public override bool CanConvert(Type objectType)
        {
            return this.GetNullableTypeOrCurrent(objectType).IsEnum;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
                return null;
            if (Enum.TryParse(this.GetNullableTypeOrCurrent(objectType), reader.Value.ToString(), out var val))
                return val;
            throw new AppUserFriendlyException($"数据：{reader.Value}不能转换成：{objectType.Name}.");
        }


        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            writer.WriteValue(value);

            if (writer.WriteState != WriteState.Array)
            {
                var pName = writer.Path.Split('.').Last();
                writer.WriteRaw(",\"" + pName + "Desc\":\"" + value.GetDesc() + "\"");
            }
        }
    }
}


